package com.yunyi.ne.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class NettyWebSocketClientHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private final WebSocketClientHandshaker handshaker;

    public NettyWebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        try {
            handshaker.handshake(ctx.channel());
            System.out.println("WebSocket handshake successful.");
        } catch (Exception e) {
            System.out.println("WebSocket handshake failed: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            log.info("Received message from server: {}", textFrame.text());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}